package com.yckj.activechicken.business.system.service.impl;

import com.yckj.activechicken.business.document.mapper.BusiDocumentMapper;
import com.yckj.activechicken.business.document.model.BusiDocument;
import com.yckj.activechicken.business.document.service.IBusiDocumentService;
import com.yckj.activechicken.business.system.mapper.SysCompanyMapper;
import com.yckj.activechicken.business.system.mapper.SysDeptMapper;
import com.yckj.activechicken.business.system.mapper.comp.SysCompanyMapperComp;
import com.yckj.activechicken.business.system.model.SysCompany;
import com.yckj.activechicken.business.system.model.SysCompanyExample;
import com.yckj.activechicken.business.system.model.SysDept;
import com.yckj.activechicken.business.system.model.SysDeptExample;
import com.yckj.activechicken.business.system.service.ISysCompanyService;
import com.yckj.activechicken.common.utils.StringUtils;
import com.yckj.activechicken.common.utils.file.FileUtils;
import com.yckj.activechicken.framework.config.ProjectConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * Title:com.yckj.activechicken.business.service.impl
 * </p>
 * <p/>
 * <p>
 * Description: 描述【公司管理业务处理层】
 * </p>
 * <p/>
 * <p>
 * Copyright: Copyright (c) 2019
 * </p>
 * <p/>
 * <p>
 * Company: 英才汇硕信息技术有限公司
 * </p>
 *
 * @author zhoujy
 * @version 1.0
 * @created 2020/5/13 17:49
 */
@Service
public class SysCompanyServiceImpl implements ISysCompanyService {
    /**
     * 获取logo上传存放目录
     */
    @Value("${upload.logoWeb}")
    private String logoWebPath;
    /**
     * 获取附件上传存放目录
     */
    @Value("${upload.appendixFile}")
    private String appendixFileFile;

    @Autowired
    private SysCompanyMapper sysCompanyMapper;

    @Autowired
    private SysCompanyMapperComp sysCompanyMapperComp;

    @Autowired
    private BusiDocumentMapper busiDocumentMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private IBusiDocumentService busiDocumentService;

    /**
     * 添加不同类型公司
     * @param sysCompany
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> addCompany(SysCompany sysCompany) {
        Map<String,String> outMap = new HashMap<>(2);

        //判断是否完全执行成功标识
        boolean logoResultFlag = true;
        boolean appendixFileResultFlag = true;

        //1、重名校验
        SysCompanyExample sysCompanyExample = new SysCompanyExample();
        sysCompanyExample.createCriteria()
                .andNameEqualTo(sysCompany.getName())
                .andDelFlagEqualTo("0");
        List<SysCompany> sysCompanyList = sysCompanyMapper.selectByExample(sysCompanyExample);
        if(StringUtils.isNotEmpty(sysCompanyList)){
            outMap.put("result","false");
            outMap.put("message","该公司已经存在，请确认！");
            return outMap;
        }

        //2、查询系统主公司，系统主公司只允许存在一条
        SysCompanyExample sysCompanyExample1 = new SysCompanyExample();
        sysCompanyExample.createCriteria().andTypeEqualTo("系统公司");
        List<SysCompany> mainSysCompany = sysCompanyMapper.selectByExample(sysCompanyExample1);

        //3、处理部门信息关系，并添加公司
        int resultNum = 0;
        String type = sysCompany.getType();
        if("系统公司".equals(type)){
            //系统公司已存在，不允许重复添加
            if(StringUtils.isNotEmpty(mainSysCompany)){
                outMap.put("result","false");
                outMap.put("message","系统公司已存在，不允许重复添加！");
                return outMap;
            }
            //添加公司信息
            resultNum = sysCompanyMapper.insertSelective(sysCompany);

            //添加系统公司为部门表根节点
            SysDept sysDept = new SysDept();
            sysDept.setParentId(0);
            sysDept.setAncestors("0");
            sysDept.setDeptName(sysCompany.getName());
            sysDept.setOrderNum(0);
            sysDept.setCreateBy(sysCompany.getCreateBy());
            sysDept.setCreateTime(sysCompany.getCreateTime());
            sysDept.setUpdateBy(sysCompany.getCreateBy());
            sysDept.setUpdateTime(sysCompany.getUpdateTime());
            sysDeptMapper.insertSelective(sysDept);
        } else if("系统子公司".equals(type)){
            //添加公司信息
            resultNum = sysCompanyMapper.insertSelective(sysCompany);

            //如果是系统子公司，需要建立主公司与子公司的关联

            //添加的是子公司，必然存在主公司，主公司parent_id为0，通过parent_id获取部门信息
            SysDeptExample sysDeptExample = new SysDeptExample();
            sysDeptExample.createCriteria().andParentIdEqualTo(0);
            List<SysDept> sysDeptList = sysDeptMapper.selectByExample(sysDeptExample);
            if(StringUtils.isEmpty(sysDeptList)){
                outMap.put("result","false");
                outMap.put("message","系统部门结构出现异常，请联系管理员处理！");
                return outMap;
            }
            SysDept sysDept = new SysDept();
            sysDept.setParentId(sysDeptList.get(0).getDeptId());
            sysDept.setAncestors("0,"+ sysDept.getParentId());
            sysDept.setDeptName(sysCompany.getName());

            //查询当前级别存在多少子公司，获取排序数值
            sysDeptExample.clear();
            sysDeptExample.createCriteria().andParentIdEqualTo(sysDept.getParentId());
            long counts = sysDeptMapper.countByExample(sysDeptExample);
            sysDept.setOrderNum((int)counts+1);

            sysDept.setCreateBy(sysCompany.getCreateBy());
            sysDept.setCreateTime(sysCompany.getCreateTime());
            sysDept.setUpdateBy(sysCompany.getCreateBy());
            sysDept.setUpdateTime(sysCompany.getUpdateTime());
            sysDeptMapper.insertSelective(sysDept);
        }

        if(resultNum == 1){
            //4、处理Logo上传业务
            Map<String,String> logoFileInfo = FileUtils.uploadFile(sysCompany.getLogoWebFile(),this.logoWebPath);
            if("true".equals(logoFileInfo.get("result"))){
                BusiDocument busiDocument = new BusiDocument();
                busiDocument.setBusiId(sysCompany.getCompanyId()+"");
                busiDocument.setDocName(logoFileInfo.get("fileName"));
                busiDocument.setDocLocalName(logoFileInfo.get("localFileName"));
                busiDocument.setDocMimeType(logoFileInfo.get("mimeType"));
                busiDocument.setDocType("公司Logo");
                //对于需要在页面展示的图片需要加入/profile路径进行处理，使用profile代理
                busiDocument.setDocUrl("/profile"+ logoFileInfo.get("uploadPath"));
                busiDocument.setRemark(sysCompany.getName()+"的Logo文件");
                busiDocument.setCreateBy(sysCompany.getCreateBy());
                busiDocument.setCreateTime(sysCompany.getCreateTime());
                busiDocument.setUpdateBy(sysCompany.getCreateBy());
                busiDocument.setUpdateTime(sysCompany.getUpdateTime());
                busiDocumentMapper.insertSelective(busiDocument);
                logoResultFlag = true;
            }else{
                logoResultFlag = false;
                outMap.put("result","false");
                outMap.put("message","公司Logo上传失败，请在修改功能中重试！");
            }

            //5、处理附件上传问题
            List<Map<String,String>> outList =  FileUtils.uploadFileList(sysCompany.getAppendixFile(),this.appendixFileFile);
            if(StringUtils.isNotEmpty(outList)){
                for(Map<String,String> map : outList){
                    if("true".equals(map.get("result"))){
                        BusiDocument busiDocument = new BusiDocument();
                        busiDocument.setBusiId(sysCompany.getCompanyId()+"");
                        busiDocument.setDocName(map.get("fileName"));
                        busiDocument.setDocLocalName(map.get("localFileName"));
                        busiDocument.setDocMimeType(map.get("mimeType"));
                        busiDocument.setDocType("公司创建附件");
                        busiDocument.setDocUrl(map.get("uploadPath"));
                        busiDocument.setRemark(sysCompany.getName()+"的创建附件");
                        busiDocument.setCreateBy(sysCompany.getCreateBy());
                        busiDocument.setCreateTime(sysCompany.getCreateTime());
                        busiDocument.setUpdateBy(sysCompany.getCreateBy());
                        busiDocument.setUpdateTime(sysCompany.getUpdateTime());
                        busiDocumentMapper.insertSelective(busiDocument);
                    }else{
                        outMap.put("result","false");
                        outMap.put("message","公司创建附件上传异常，请在修改功能中查看附件信息！");
                        appendixFileResultFlag = false;
                    }
                }
            }
        }else {
            outMap.put("result","false");
            outMap.put("message","公司信息创建失败，请联系管理员！");
        }

        if(logoResultFlag && appendixFileResultFlag){
            outMap.put("result","true");
            outMap.put("message","公司信息创建成功！");
        }
        return outMap;
    }

    /**
     * 修改公司信息，包括logo图片处理
     * @param sysCompany
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> modfiyCompany(SysCompany sysCompany) {
        Map<String,String> outMap = new HashMap<>(2);

        //1、修改公司基础信息
        int resultNum = sysCompanyMapper.updateByPrimaryKeySelective(sysCompany);

        if(resultNum == 1){
            //2、处理Logo上传业务
            //先上传新的图片内容
            Map<String,String> logoFileInfo = FileUtils.uploadFile(sysCompany.getLogoWebFile(),this.logoWebPath);
            //获取旧的logo信息
            BusiDocument oldBusiDocument = new BusiDocument();
            oldBusiDocument.setBusiId(sysCompany.getCompanyId()+"");
            oldBusiDocument.setDocType("公司Logo");
            List<BusiDocument> list = busiDocumentService.queryDocByCompanyId(oldBusiDocument);
            if("true".equals(logoFileInfo.get("result"))){
                //更新文档记录的信息，记录新logo信息
                if(StringUtils.isNotEmpty(list)){
                    //存放旧的文档信息
                    oldBusiDocument = list.get(0);
                    BusiDocument busiDocument = new BusiDocument();
                    busiDocument.setDocId(oldBusiDocument.getDocId());
                    busiDocument.setDocName(logoFileInfo.get("fileName"));
                    busiDocument.setDocLocalName(logoFileInfo.get("localFileName"));
                    busiDocument.setDocMimeType(logoFileInfo.get("mimeType"));
                    //对于需要在页面展示的图片需要加入/profile路径进行处理，使用profile代理
                    busiDocument.setDocUrl("/profile"+ logoFileInfo.get("uploadPath"));
                    busiDocument.setRemark("更新" + sysCompany.getName()+"的Logo文件");
                    busiDocument.setUpdateBy(sysCompany.getUpdateBy());
                    busiDocument.setUpdateTime(sysCompany.getUpdateTime());
                    busiDocumentMapper.updateByPrimaryKeySelective(busiDocument);

                    //删除旧的Logo图片文件
                    String oldLogoPath = oldBusiDocument.getDocUrl();
                    //需要将/profile代理路径截取，之后的路径才是真实路径
                    String delPath = ProjectConfig.getProfile() + oldLogoPath.substring(8);
                    FileUtils.deleteFile(delPath);
                    outMap.put("result","true");
                    outMap.put("message","公司信息更新成功！");
                }else {
                    outMap.put("result","false");
                    outMap.put("message","未查询到该公司的Logo记录信息，请核实！");
                }
            }else{
                outMap.put("result","false");
                outMap.put("message","公司Logo上传失败，请重试！");
            }
        }else {
            outMap.put("result","false");
            outMap.put("message","公司信息修改失败，请联系管理员！");
        }

        return outMap;
    }

    /**
     * 多条件查询公司信息
     * @param sysCompany
     * @return
     */
    @Override
    public List<SysCompany> listCompany(SysCompany sysCompany) {
        return sysCompanyMapperComp.selectCompanyCond(sysCompany);
    }

    /**
     * 删除公司信息，解除部门关系
     * @param sysCompany
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delCompany(SysCompany sysCompany) {
        //修改公司删除标识为1
        sysCompany.setDelFlag("1");
        sysCompanyMapper.updateByPrimaryKeySelective(sysCompany);

        //修改部门关系表状态为1
        SysDept sysDept = new SysDept();
        sysDept.setDelFlag("1");
        sysDept.setUpdateBy(sysCompany.getUpdateBy());
        sysDept.setUpdateTime(sysCompany.getUpdateTime());

        SysDeptExample sysDeptExample = new SysDeptExample();
        sysDeptExample.createCriteria().andDeptNameEqualTo(sysCompany.getName());

        int num = sysDeptMapper.updateByExampleSelective(sysDept,sysDeptExample);
        return num;
    }
}
